package com.zzsy.carosshopprojects.service;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;

import com.king.base.util.ToastUtils;
import com.yzy.voice.VoicePlay;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.BaseBean;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.bean.OrderDetialBean;
import com.zzsy.carosshopprojects.bean.RechargeOrderDetialBean;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.ApkInfoUtil;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.FormatTimeUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.sunmiprint.PrintHelper;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;


/**
 * Created by Administrator on 2018/7/4 0004.
 */

public class CusReceiver extends BroadcastReceiver {


    private Intent intent;
    private Context mContext;
    private String qrSwitch;
    private String rechargeBalanceDou;
    private String gzhSwitch;
    private double redPackedAmountDou;
    private double redPackedSumDou;
    private double goodsCouponAmountDou;
    private String certificationTypeName;
    private String carNumber;
    private String musicSwitch;

    @Override
    public void onReceive(Context context, Intent intent) {
        String versionData = ApkInfoUtil.getVersionData();
        /**
         * P2屏幕唤醒
         */
        if (!StringUtils.isEmpty(versionData)) {
            if ("P1_4G".equals(versionData)) {
            } else {
                ScreenWake(context);
            }
        } else {
            ScreenWake(context);
        }

        //获取开具发票开关
        try {
            qrSwitch = DataUtil.getInstance().getQrSwitch();
        } catch (Exception e) {
            qrSwitch = "";
        }

        try {
            //获取开具发票开关
            gzhSwitch = DataUtil.getInstance().getGzhSwith();
        } catch (Exception e) {
            gzhSwitch = "0";
        }

        try {
            //获取语音播报开关
            musicSwitch = DataUtil.getInstance().getMusicSwitch();
        } catch (Exception e) {
            musicSwitch = "";
        }

        Bundle bundle = intent.getExtras();
        String action = intent.getAction();
        this.mContext = context;
        if (bundle == null || action == null) {

            return;
        }


        switch (action) {
            case JPushInterface.ACTION_REGISTRATION_ID:

                break;

            case JPushInterface.ACTION_MESSAGE_RECEIVED:

                break;

            case JPushInterface.ACTION_NOTIFICATION_RECEIVED:

                processMessage(bundle, context);
                break;

            case JPushInterface.ACTION_NOTIFICATION_OPENED:

                //gotoActivity(context);
                break;

            case JPushInterface.ACTION_RICHPUSH_CALLBACK:

                break;

            case JPushInterface.ACTION_CONNECTION_CHANGE:

                break;

            default:
                break;
        }
    }


    //打印所有intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {

                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:").append(key).append(", value: [").append(myKey).append(" - ").append(json.optString(myKey)).append("]");
                    }
                } catch (JSONException e) {

                }

            } else {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getString(key));
            }
        }
        return sb.toString();
    }


    private void processMessage(Bundle bundle, Context context) {
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        if (null == extras || extras.trim().length() == 0) {
            return;
        }
        try {
            JSONObject json = new JSONObject(extras);
            Iterator<String> it = json.keys();

            Map<String, String> map = new HashMap<>();
            while (it.hasNext()) {
                String key = it.next();
                map.put(key, json.optString(key));
            }
            // 是否打印首页未打印订单
            // SPHelper.setSimpleKeyValue(context, "isPrint", false);

            if (!StringUtils.isEmpty(map.get("type"))) {
                switch (map.get("type")) {
                    case "2"://一键加油
                        String orderAmount = map.get("orderAmount");
                        String payAmount = map.get("payAmount");
                        String activityReduction = map.get("activityReduction");
                        String extractedCode = map.get("extractedCode");
                        String oilNum = map.get("oilNum");
                        String time = map.get("time");
                        String orderId = map.get("orderNumber");
                        String rebate = map.get("rebate");
                        String phone = map.get("phone");
                        String pageSkip = map.get("pageSkip");
                        if (!StringUtils.isEmpty(musicSwitch)) {
                            if ("1".equals(musicSwitch)) {
                                MusicTell(orderAmount);
                            }
                        }

                        /**
                         * 调取订单详情
                         * */
                        IsPrintTicket(orderId, map);
                        //   getOrderDelatil(orderAmount, payAmount, activityReduction, extractedCode, oilNum, time, orderId, rebate, phone, pageSkip);

                        break;

                    case "3":
                        String rechargeNumber = map.get("rechargeNumber");
                        String amount = map.get("amount");
                        String storeName = map.get("storeName");
                        String payTypeReghter = map.get("payType");
                        String orderCreateTime = map.get("orderCreateTime");
                        String memberCouponAmounts = map.get("memberCouponAmounts");
                        String memberBlanceAmounts = map.get("memberBlanceAmounts");
                        if (StringUtils.isEmpty(memberBlanceAmounts)) {
                            memberBlanceAmounts = "0";
                        }
                        if (StringUtils.isEmpty(memberCouponAmounts)) {
                            memberCouponAmounts = "0";
                        }

//                        if (!StringUtils.isEmpty(musicSwitch)) {
//                            if ("1".equals(musicSwitch)) {
//                                MusicTell(amount);
//                            }
//                        }
                        String memberBlanceAmountsDou = ConverterHelper.toBigDecimal(memberBlanceAmounts).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                        String memberCouponAmountsDou = ConverterHelper.toBigDecimal(memberCouponAmounts).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                        //  getOrderDetialData(rechargeNumber, amount, storeName, orderCreateTime, payTypeReghter, memberBlanceAmountsDou, memberCouponAmountsDou);
                        setReghterData(map);
                        break;

                    case "4"://消费
                        String fOrderAmount = map.get("orderAmount");
                        String fPayAmount = map.get("payAmount");
                        String fActivityReduction = map.get("activityReduction");
                        String fExtractedCode = map.get("extractedCode");
                        String fOilNum = map.get("oilNum");
                        String fTime = map.get("time");
                        String fOrderId = map.get("orderNumber");
                        String fRebate = map.get("rebate");
                        String payType = map.get("payType");

                        if (!StringUtils.isEmpty(musicSwitch)) {
                            if ("1".equals(musicSwitch)) {
                                MusicTell(fPayAmount);
                            }
                        }
                        /**支付成功 通知界面刷新**/
                        EventBus.getDefault().post(new MessageEvent(MessageEvent.PAYSUCESS));
                        IsPrintTicket(fOrderId, map);
                        //  getOrderDetialDataTwo(fOrderAmount, fPayAmount, fOilNum, fTime, fOrderId, payType);

                        break;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 语音播报
     */
    private void MusicTell(String payAmount) {
        //String amounts = ConverterHelper.toBigDecimal(payAmount).divide(ConverterHelper.toBigDecimal(100)).toString();
        VoicePlay.with(mContext).play(payAmount, false);
    }

    /**
     * 充值、
     */
    private void setReghterData(Map<String, String> map) {
        String rechargeNumber = map.get("rechargeNumber");
        String amount = map.get("amount");
        if (!StringUtils.isEmpty(amount)) {
            if (!StringUtils.isEmpty(musicSwitch)) {
                if ("1".equals(musicSwitch)) {
                    VoicePlay.with(mContext).play(amount, false);
                }
            }
        }
        /**充值成功 通知界面刷新**/
        EventBus.getDefault().post(new MessageEvent(MessageEvent.RECHARGESUCESS));

        IsPrintRechargeTicket(rechargeNumber, map);
    }

    /**
     * 查询是否可以打印小票
     *
     * @param
     * @param orderNumber 订单编号
     */
    public void IsPrintTicket(String orderNumber, Map<String, String> map) {
        RequestUtils.UpdatePrintStatus(mContext, orderNumber, new MyObserver<BaseBean>(mContext, false) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (code == ConfigureFile.code) {
                    if ("2".equals(map.get("type"))) {//一键加油
                        getOrderDetail(2, orderNumber, map);
                    } else if ("4".equals(map.get("type"))) {//操作员收费成功后的小票
                        getOrderDetail(4, orderNumber, map);
                    }

                } else {
                    ToastUtils.showToast(mContext, errorMsg);
                }
            }
        });
    }

    /**
     * 查询是否可以打印充值小票
     *
     * @param orderNumber
     * @param map
     */
    public void IsPrintRechargeTicket(String orderNumber, Map<String, String> map) {
        RequestUtils.UpdatePrintStatus(mContext, orderNumber, new MyObserver<BaseBean>(mContext, false) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (code == ConfigureFile.code) {
                    String rechargeNumber = map.get("rechargeNumber");
                    String amount = map.get("amount");
                    String storeName = map.get("storeName");
                    String payTypeReghter = map.get("payType");
                    String orderCreateTime = map.get("orderCreateTime");
                    String memberCouponAmounts = map.get("memberCouponAmounts");
                    String memberBlanceAmounts = map.get("memberBlanceAmounts");
                    if (StringUtils.isEmpty(memberBlanceAmounts)) {
                        memberBlanceAmounts = "0";
                    }
                    if (StringUtils.isEmpty(memberCouponAmounts)) {
                        memberCouponAmounts = "0";
                    }
                    String memberBlanceAmountsDou = ConverterHelper.toBigDecimal(memberBlanceAmounts).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    String memberCouponAmountsDou = ConverterHelper.toBigDecimal(memberCouponAmounts).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    getOrderDetialData(rechargeNumber, amount, storeName, orderCreateTime, payTypeReghter, memberBlanceAmountsDou, memberCouponAmountsDou);
                } else {
                    ToastUtils.showToast(mContext, errorMsg);
                }
            }
        });
    }


    /**
     * 调取充值订单详情
     *
     * @param rechargeNumber
     * @param amount
     * @param storeName
     * @param orderCreateTime
     * @param payTypeReghter
     * @param memberBlanceAmountsDou
     * @param memberCouponAmountsDou
     */

    private void getOrderDetialData(String rechargeNumber, String amount, String storeName, String orderCreateTime, String payTypeReghter, String memberBlanceAmountsDou, String memberCouponAmountsDou) {
        RequestUtils.GetROrder(mContext, rechargeNumber, new MyObserver<RechargeOrderDetialBean>(mContext) {
            @Override
            public void onSuccess(RechargeOrderDetialBean bean) {
                if (bean != null) {
                    String printStatus = bean.getPrintStatus();
                    String memberPhone = bean.getPhone();
                    String rechargeBalance = bean.getRechargeBalance();
                    if (!StringUtils.isEmpty(rechargeBalance)) {
                        rechargeBalanceDou = ConverterHelper.toBigDecimal(rechargeBalance).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    } else {
                        rechargeBalanceDou = "0";
                    }
                    String oilType = "";
                    if (bean.getProductId() != null) {
                        if (bean.getProductId().equals("1")) {
                            oilType = "柴油";
                        } else if (bean.getProductId().equals("2")) {
                            oilType = "汽油";
                        } else if (bean.getProductId().equals("25")) {
                            oilType = "LNG";
                        } else if (bean.getProductId().equals("26")) {
                            oilType = "CNG";
                        }
                    }
                    String redPackedAmount = bean.getRedPackedAmount();
                    String redPackedSum = bean.getRedPackedSum();
                    if (StringUtils.isEmpty(redPackedAmount)) {
                        redPackedAmount = "0";
                    }
                    redPackedAmountDou = ConverterHelper.toBigDecimal(redPackedAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    redPackedSumDou = ConverterHelper.toBigDecimal(redPackedSum).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    String goodsCouponAmount = bean.getGoodsCouponAmount();
                    if (StringUtils.isEmpty(goodsCouponAmount)) {
                        goodsCouponAmount = "0";
                    }
                    goodsCouponAmountDou = ConverterHelper.toBigDecimal(goodsCouponAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    if (StringUtils.isEmpty(memberPhone)) {
                        memberPhone = "";
                    }
                    String amounts = ConverterHelper.toBigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    String payTypeStr = "";
                    String time = "";
                    if (!StringUtils.isEmpty(orderCreateTime)) {
                        time = FormatTimeUtil.formatTimeStamp2DateStr(String.valueOf(Long.parseLong(orderCreateTime) / 1000), "yyyy-MM-dd HH:mm:ss");
                    }
                    if ("1".equals(payTypeReghter)) {
                        payTypeStr = "支付宝支付";
                    } else if ("2".equals(payTypeReghter)) {
                        payTypeStr = "微信支付";
                    } else if ("3".equals(payTypeReghter)) {
                        payTypeStr = "银联支付";
                    } else if ("4".equals(payTypeReghter)) {
                        payTypeStr = "余额支付";
                    } else if ("5".equals(payTypeReghter)) {
                        payTypeStr = "现金支付";
                    }
                    Log.d("xxxxxx", printStatus + "---");
                    if (!StringUtils.isEmpty(printStatus)) {
//                        if ("0".equals(printStatus)) {
//                            PrintHelper.getInstance().PrintRechargeOrder(rechargeNumber, time, amounts, storeName, payTypeStr, Double.valueOf(rechargeBalanceDou), memberPhone,
//                                    redPackedAmountDou, goodsCouponAmountDou, redPackedSumDou, oilType, bean.getReductionCouponAmount(),false);
//                        }
                        PrintHelper.getInstance().PrintRechargeOrder(rechargeNumber, time, amounts, storeName, payTypeStr, Double.valueOf(rechargeBalanceDou), memberPhone,
                                redPackedAmountDou, goodsCouponAmountDou, redPackedSumDou, oilType, bean.getReductionCouponAmount(), false);
                    }
                }

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(mContext, errorMsg);
            }
        });


    }


    /**
     * 获取订单详情接口
     *
     * @param
     * @param orderNumber
     */
    public void getOrderDetail(int kind, String orderNumber, Map<String, String> map) {
        RequestUtils.OrderDetail(mContext, orderNumber, new MyObserver<OrderDetialBean>(mContext, false) {
            @Override
            public void onSuccess(OrderDetialBean result) {
                if (kind == 2) {

                    String orderAmount = map.get("orderAmount");
                    String payAmount = map.get("payAmount");
                    String activityReduction = map.get("activityReduction");
                    String extractedCode = map.get("extractedCode");
                    String oilNum = map.get("oilNum");
                    String time = map.get("time");
                    String orderId = map.get("orderNumber");
                    String rebate = map.get("rebate");
                    String phone = map.get("phone");
                    String pageSkip = map.get("pageSkip");

                    if (StringUtils.isEmpty(activityReduction)) {
                        activityReduction = "";
                    }
                    if (StringUtils.isEmpty(orderAmount)) {
                        orderAmount = "";
                    }
                    if (StringUtils.isEmpty(payAmount)) {
                        payAmount = "";
                    }
                    String oilPrice = result.getOilPrice();
                    double oilsPrices;
                    if (!StringUtils.isEmpty(oilPrice)) {
                        BigDecimal bigDecimalAmount = ConverterHelper.toBigDecimal(oilPrice).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        oilsPrices = bigDecimalAmount.doubleValue();

                    } else {

                        oilsPrices = 0;
                    }
                    String printStatus = result.getPrintStatus();
                    String payType = result.getPayType();
                    String payTypeStr = "";
                    if (!StringUtils.isEmpty(payType)) {
                        if ("1".equals(payType)) {
                            payTypeStr = "支付宝支付";
                        } else if ("2".equals(payType)) {
                            payTypeStr = "微信支付";
                        } else if ("3".equals(payType)) {
                            payTypeStr = "银联支付";
                        } else if ("4".equals(payType)) {
                            payTypeStr = "余额支付";
                        }
                    }
                    String title = "";
                    if (StringUtils.isEmpty(result.getPayRule())) {
                        title = "消费凭证(一键加油)";
                    } else {
                        if (result.getPayRule().equals("6"))
                            title = "消费凭证(快捷加油)";
                        else
                            title = "消费凭证(一键加油)";
                    }
                    PrintHelper.getInstance().getPrintOrder(title,orderAmount, payAmount, result.getStoreName(), Double.valueOf(activityReduction),
                            oilNum, time, orderId, phone, payTypeStr,
                            Double.valueOf(result.getRise()), oilsPrices, result.getOilPriceSwitch(), result.getCertificationTypeName(), result.getCarNumber(), false);

                } else if (kind == 4) {
                    PrintHelper.getInstance().PrintOperatorChargeTicket(result, false);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(mContext, errorMsg);
            }
        });


    }

    /**
     * 屏幕唤醒
     *
     * @param
     */
    public void ScreenWake(Context context) {
        try {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire();
            wl.release();
        } catch (Exception e) {
            Log.d("dddd", "唤醒屏幕错误");
        }

    }

}
